package tk.djcrazy.instantmessage.serviceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import tk.djcrazy.instantmessage.domain.ChatMessage;
import tk.djcrazy.instantmessage.domain.UserEntity;
import tk.djcrazy.instantmessage.service.IChatMessageService;
import tk.djcrazy.instantmessage.service.IUserService;

public class ChatMessageServiceImpl implements IChatMessageService{
	private IUserService userService;
	private static final Map<Integer, List<ChatMessage>> MESSAGE_MAP = 
			new ConcurrentHashMap<Integer, List<ChatMessage>>(256);
	
	public  void addMessage(int fromUserId, int toUserId, String content) {
		System.out.println("addMessage:"+fromUserId+" "+toUserId+" "+content);
		ChatMessage mChatMessage = new ChatMessage();
		mChatMessage.setMessageContent(content);
		mChatMessage.setSendTime(new Date());
 		mChatMessage.setSenderId(fromUserId);
 		mChatMessage.setSenderName(userService.findById(fromUserId).getUserName());
		mChatMessage.setReceiver(toUserId);
		System.out.println(MESSAGE_MAP.size()+"aaaaaa");
		if (!MESSAGE_MAP.containsKey(toUserId)) {
			List<ChatMessage> list = new ArrayList<ChatMessage>();
			list.add(mChatMessage);
			MESSAGE_MAP.put(toUserId, list);
		} else {
			MESSAGE_MAP.get(toUserId).add(mChatMessage);
		}
		System.out.println(MESSAGE_MAP.size());
	}
	
	public  List<ChatMessage> getMessages(int userId) {
		List<ChatMessage> list = MESSAGE_MAP.get(userId);
		MESSAGE_MAP.remove(userId);
		return list;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
}
